import React from 'react';
import { Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import { navigate } from 'utils/router';
import sha1 from 'sha1';
import './index.scss';
import intl from '../../../../../../../../../locale';

export default class Read extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      showNext: false,
      // 位置固定时百分比
      fixedPercent: null,
    };
  }

  goNextFile = () => {
    const { diffs } = this.props;
    let firstPath = '';
    for (let i = 0; i < diffs.length; i++) {
      const curFile = diffs[i];
      if (!curFile.read) {
        firstPath = curFile.new_path;
        break;
      }
    }
    this.setState({
      showNext: true,
    });

    console.error(firstPath);
    firstPath && this.goFile(firstPath);
  };

  goFile = (path) => {
    const { pathResource } = window.FORCE;
    const { codeReviewDetail, forceCrFileViewType } = this.props;
    const curPath = `/${pathResource.fullPath}/merge_request/${codeReviewDetail.id}`;
    if (window.location.pathname !== `${curPath}/changes`) {
      navigate(`${curPath}/changes`);
      this.props.changeMrTabKey('changes');
    }
    window.location.hash = `#file=${sha1(path)}`;
    // 如果是单文件切换文件，滚动条滚动到顶部
    if (forceCrFileViewType === 'single') {
      document.querySelector('#mr-content-body').scrollTop = 0;
    }
  };

  close = () => {
    this.setState({
      showNext: false,
      fixedPercent: null,
    });
  };

  render() {
    const {
      diffs,
      isNavHidden,
      isPushRecordsFetched,
      commits,
      from_commit,
      to_commit,
      isTooLarge,
      leftWidth,
      fixWidth,
    } = this.props;
    // 选择全部区间时才有阅读进度
    if (
      !(
        isPushRecordsFetched &&
        diffs &&
        diffs.length &&
        commits &&
        commits.length &&
        from_commit === commits[0].id &&
        to_commit === commits[commits.length - 1].id
      )
    ) {
      return null;
    }

    const { showNext, fixedPercent } = this.state;
    const readCount = diffs.filter((diff) => {
      return diff.read;
    });
    const rate = (readCount.length / diffs.length) * 100;
    const percent = rate > 0 && rate < 1 ? 1 : Math.floor(rate);
    const tooltipPercent = fixedPercent === null ? percent : fixedPercent || 0;
    const tooltipStyle =
      tooltipPercent < 50
        ? {
            left: `${tooltipPercent}%`,
          }
        : {
            right: `${100 - tooltipPercent}%`,
          };
    return (
      <div
        style={{
          top: isTooLarge ? '169px' : '134px',
          left: leftWidth ? `${parseInt(leftWidth)}px` : `${parseInt(fixWidth) + 300}px`,
        }}
        className={`mr-read ${isNavHidden ? 'no-nav' : 'has-nav'}`}
      >
        <div className="mr-read-progress">
          <div style={{ width: `${percent}%` }} className="mr-read-progress-content" />
        </div>
        <div className={`mr-read-tooltip ${showNext ? 'next' : ''}`} style={tooltipStyle}>
          <div className={`mr-read-tooltip-text ${percent === 100 ? 'completed' : ''}`}>
            <span className="gray">
              {intl.get({ id: 'code-assets.components.read.Read', defaultMessage: '已读' })}
            </span>
            &nbsp;
            <span>
              {readCount.length} / {diffs.length}
            </span>
          </div>
          {showNext ? (
            <React.Fragment>
              <Balloon.Tooltip
                trigger={
                  <div
                    className={`go-next-icon ${percent === 100 ? 'completed' : ''}`}
                    onClick={this.goNextFile}
                  >
                    <YunxiaoIcon type="arrow-down-line" />
                  </div>
                }
                align="b"
                text={intl.get({
                  id: 'code-assets.components.read.GoToTheNextUnread',
                  defaultMessage: '前往下一个未读文件',
                })}
              />

              <div className="close-icon" onClick={this.close}>
                <YunxiaoIcon type="false-line" />
              </div>
            </React.Fragment>
          ) : (
            <Balloon.Tooltip
              trigger={
                <div
                  className={`go-first-icon ${percent === 100 ? 'completed' : ''}`}
                  onClick={() => {
                    this.setState({
                      fixedPercent: percent,
                    });

                    this.goNextFile();
                  }}
                >
                  <YunxiaoIcon type="anchor-line" />
                </div>
              }
              align="b"
              text={intl.get({
                id: 'code-assets.components.read.LocateUnreadFile',
                defaultMessage: '定位至未读文件',
              })}
            />
          )}
        </div>
      </div>
    );
  }
}
